#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import rospy

from database.account_sqlite3 import Auth_Parser

from tool import Log_Parser
 
log = Log_Parser()

'''
    帐号密码相关
    创建时间：2020/12/30
    修改时间：2022/9/26
    修改时间：2023/1/19
'''

class Account_Parser:
    """用户登陆类
    """    
    
    def __init__(self):
        """初始化
        """    
        self.__node_name = "Account_Parser"
    
    def InitParser(self, node_name):
        """初始化
        Args:
            node_name (_type_): 节点名字
        """        
        self.__node_name = node_name # node name配置
        self.__account_sql = Auth_Parser() #用户sql连接

    def GetNodeName(self):
        """获取节点名称

        Returns:
            _type_: 节点名称
        """        
        return self.__node_name

    def LoginAccount(self,data):
        """帐号登录

        Args:
            data (_type_): _description_

        Raises:
            Exception: Request data error!
            Exception: name is empty!
            Exception: password is empty!
            Exception: name is error!
            Exception: password is error!

        Returns:
            _type_: _description_
        """        

        ret_dat = {};ret_dat["msg"]='success';ret_dat["code"]=0
        try:
            if not data: raise Exception("Request data error!")
            if not data["name"]: raise Exception("name is empty!")
            if not data["password"]: raise Exception("password is empty!")
            
            user_name = data["name"]
            password = data["password"]
            user_dic = self.__account_sql.GetAccountData()
            if user_name not in user_dic: raise Exception("name is error!")
            if password != user_dic[user_name]: raise Exception("password is error!")
            
            log_msg = "[Account_Parser]Account<{}> log in.".format(user_name)
            log.LogInfo(self.GetNodeName(),log_msg)     
        except Exception as error:
            ret_dat["code"]=-1
            ret_dat["msg"]=str(error)
        
            err_msg = "[Account_Parser]Failed to login: {}".format(str(error))
            log.LogError(self.GetNodeName(),err_msg)  
            rospy.logerr(err_msg)
        finally:
            return ret_dat

    def ListAccount(self):
        '''
            帐号列表查询
        '''
        ret_dat = {};ret_dat["msg"]='success';ret_dat["code"]=0
        try:
            account_list=[]
            user_dic = self.__account_sql.GetAccountData()
            if user_dic:
                for account in user_dic.keys():
                    user_one={}
                    user_one["name"]=account
                    user_one["password"]=user_dic[account][0]
                    user_one["perm"]=user_dic[account][1]
                    account_list.append(user_one)
                
                # 是否添加admin 20230701-dw.liu
                flag = False # 默认不存在
                for account in user_dic.keys():
                    if account == "admin":
                        flag = True # 已经存在
                if not flag:
                    user_one = {}
                    user_one["name"]= "admin"
                    user_one["password"]="123456"
                    user_one["perm"]="admin"
                    account_list.append(user_one)
                    self.__account_sql.CreateAccount(user_one["name"],user_one["password"],user_one["perm"]) # 数据库存储 20230824-dw.liu

                # 是否添加test 20230701-dw.liu
                flag = False # 默认不存在
                for account in user_dic.keys():
                    if account == "test":
                        flag = True # 已经存在
                if not flag:
                    user_one = {}
                    user_one["name"]= "test"
                    user_one["password"]="123456"
                    user_one["perm"]="opera"
                    account_list.append(user_one)
                    self.__account_sql.CreateAccount(user_one["name"],user_one["password"],user_one["perm"]) # 数据库存储 20230824-dw.liu

                ret_dat["account_list"]=account_list
            else: #提供默认账户、密码

                user_one={}
                user_one["name"]="aoting"
                user_one["password"]="aoting"
                user_one["perm"]="admin"
                account_list.append(user_one)

                self.__account_sql.CreateAccount(user_one["name"],user_one["password"],user_one["perm"]) # 数据库存储 20230824-dw.liu

                # 提供admin 20230701-dw.liu
                user_one = {}
                user_one["name"]= "admin"
                user_one["password"]="123456"
                user_one["perm"]="admin"
                account_list.append(user_one)

                self.__account_sql.CreateAccount(user_one["name"],user_one["password"],user_one["perm"]) # 数据库存储 20230824-dw.liu

                # 提供test 20230701-dw.liu
                user_one = {}
                user_one["name"]= "test"
                user_one["password"]="123456"
                user_one["perm"]="opera"
                account_list.append(user_one)

                self.__account_sql.CreateAccount(user_one["name"],user_one["password"],user_one["perm"]) # 数据库存储 20230824-dw.liu

                ret_dat["account_list"]=account_list
        except Exception as error:
            # ret_dat["ret"]='fail'
            ret_dat["code"]=-1
            ret_dat["msg"]=str(error)

            err_msg = "[Account_Parser]Failed to list account: {}".format(str(error))
            log.LogError(self.GetNodeName(),err_msg)  
            rospy.logerr(err_msg)
        finally:
            return ret_dat
    
    def CreateAccount(self,data):
        '''
            创建帐号密码
        '''
        #ret_dat = {};ret_dat["ret"]='success';ret_dat["code"]=0
        ret_dat = {};ret_dat["msg"]='success';ret_dat["code"]=0
        try:
            if not data: raise Exception("Request data error!")
            if not data["name"]: raise Exception("name is empty!")
            if not data["key"]: raise Exception("key is empty!")
            if not data["perm"]: raise Exception("perm is empty!")

            user_name = data["name"]
            key = data["key"]
            perm = data["perm"] 
            if perm not in self.__account_sql.GetPermission():
                 raise Exception("Permission value error!")
            state,msg = self.__account_sql.CreateAccount(user_name,key,perm)    
            if not state: raise Exception(msg)  
  
            log_msg = "[Account_Parser]Account<{}> is created.".format(user_name)
            log.LogInfo(self.GetNodeName(),log_msg)     
        except Exception as error:
            #ret_dat["ret"]='Fail'
            ret_dat["code"]=-1
            ret_dat["msg"]=str(error)

            err_msg = "[Account_Parser]Failed to create a new account: {}".format(str(error))
            log.LogError(self.GetNodeName(),err_msg)  
            rospy.logerr(err_msg)
        finally:
            return ret_dat

    def ModifyAccount(self,data):
        '''
            修改帐号密码
        '''
        ret_dat = {};ret_dat["msg"]='success';ret_dat["code"]=0
        try:
            if not data: raise Exception("Request data error!")
            if not data["name"]: raise Exception("name is empty!")
            if not data["new_password"]: raise Exception("new_password is empty!")
            if not data["perm"]: raise Exception("perm is empty!")

            user_name = data["name"]
            new_password = data["new_password"]
            perm = data["perm"] 

            user_dic = self.__account_sql.GetAccountData()
            if user_name not in user_dic.keys(): raise Exception("The account does not exist!") 

            if perm not in self.__account_sql.GetPermission():
                 raise Exception("Permission value error!")

            state,msg = self.__account_sql.CreateAccount(user_name,new_password,perm)
            if not state: raise Exception(msg)

            log_msg = "[Account_Parser]Account<{}> is modified.".format(user_name)
            log.LogInfo(self.GetNodeName(),log_msg)   
        except Exception as error:
            #ret_dat["ret"]='Fail'
            ret_dat["code"]=-1
            ret_dat["msg"]=str(error)

            err_msg = "[Account_Parser]Failed to modify account: {}".format(str(error))
            log.LogError(self.GetNodeName(),err_msg)  
            rospy.logerr(err_msg)
        finally:
            return ret_dat

    def DeleteAccount(self,data):
        '''
            删除帐号密码
        '''
        ret_dat = {};ret_dat["msg"]='success';ret_dat["code"]=0
        try:
            if not data: raise Exception("Request data error!")
            if not data["name"]: raise Exception("name is empty!")
            user_name = data["name"]

            user_dic=self.__account_sql.GetAccountData()
            if user_name not in user_dic.keys(): 
                raise Exception("The account does not exist!") 
            state,msg = self.__account_sql.DeleteAccount(user_name)
            if not state: raise Exception(msg)   
            
            log_msg = "[Account_Parser]Account<{}> is deleted.".format(user_name)
            log.LogInfo(self.GetNodeName(),log_msg)   
        except Exception as error:
            ret_dat["code"]=-1
            ret_dat["msg"]=str(error)

            err_msg = "[Account_Parser]Failed to delete account: {}".format(str(error))
            log.LogError(self.GetNodeName(),err_msg)  
            rospy.logerr(err_msg)
        finally:
            return ret_dat

